package netty.http;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;

import java.net.URI;
import java.nio.charset.StandardCharsets;

/**
 * \* User: Administrator
 * <p>
 * \* Date: 2020/10/28
 * <p>
 * \* Time: 11:15
 * <p>
 * \* Description:
 * \
 */
public class HttpClient {
    public void connect(String host, int port) throws Exception {
        NioEventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpResponseDecoder())
                                .addLast(new HttpRequestEncoder())
                                .addLast(new HttpClientHandler());
                    }
                });
        ChannelFuture channelFuture = bootstrap.connect(host, port).sync();

        URI uri = new URI("http://127.0.0.1:8099");
        String content = "hello netty";
        DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());

        Unpooled.wrappedBuffer(content.getBytes(StandardCharsets.UTF_8));

        request.headers().set(HttpHeaderNames.HOST, host)
                .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE)
                .set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());

        channelFuture.channel().write(request);
        channelFuture.channel().flush();
        channelFuture.channel().closeFuture().sync();
    }

    public static void main(String[] args) throws Exception {
        HttpClient httpClient = new HttpClient();
        httpClient.connect("127.0.0.1", 8099);
    }
}
